package com.qf.fcy.youshare.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.qf.fcy.youshare.Constants;
import com.qf.fcy.youshare.DataStorage;
import com.qf.fcy.youshare.R;
import com.qf.fcy.youshare.SubCategoryActivity;
import com.qf.fcy.youshare.adapter.StorePlatformAdapter;
import com.qf.fcy.youshare.model.Category;
import com.qf.fcy.youshare.model.Product;
import com.qf.fcy.youshare.task.ProductListTask;
import com.qf.fcy.youshare.utils.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Alex[FR]
 * Date: 2015/2/5
 * Email: alex_fcy@163.com
 */
public class StorePlatformFragment extends Fragment implements TaskProcessor, AdapterView.OnItemClickListener {
    private boolean hasFirstLoad;
    private List<Product> products;
    private StorePlatformAdapter adapter;
    /**
     * 子分类ID，如果这个id没有设置，那么就显示的是平台商品列表，就需要包含分类九宫格
     * 如果设置了，那么就是显示特定分类下的商品列表
     * 不需要显示分类九宫格了
     */
    private String categoryId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        products = new LinkedList<Product>();

        Bundle arguments = getArguments();
        if (arguments != null) {
            categoryId = arguments.getString(Constants.INTENT_KEY_CATEGORY_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View ret = inflater.inflate(R.layout.fragment_store_platform, container, false);

        //-------- 商品部分九宫格界面 ------------
        GridView gridView = (GridView) ret.findViewById(R.id.store_platform_products);
        adapter = new StorePlatformAdapter(getActivity(), products);
        gridView.setAdapter(adapter);

        //-------- 分类部分九宫格界面 ------------
        GridView catGrid = (GridView) ret.findViewById(R.id.store_platform);
        // 如果有分类ID, 那么隐藏
        if (categoryId != null) {
            catGrid.setVisibility(View.GONE);
        }

        List<Map<String, Object>> data = new LinkedList<Map<String, Object>>();
        DataStorage dataStorage = DataStorage.getInstance();
        // 平台产品id为2
        Category category = dataStorage.getCategory("2");
        if (category != null) {
            List<Category> subCategories = category.getSubCategory();
            for (int i = 0; i < subCategories.size(); i++) {
                Category subCat = subCategories.get(i);
                String name = subCat.getName();
                String id = subCat.getId();

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                //TODO 根据id设置图片---
                map.put("icon", R.drawable.product_default);
                data.add(map);

            }

        }

        SimpleAdapter catAdapter = new SimpleAdapter(
                getActivity(), data,
                R.layout.item_plaform_category,
                new String[]{"name", "icon"},
                new int[]{R.id.item_platform_title, R.id.item_platform_icon});
        catGrid.setAdapter(catAdapter);
        catGrid.setOnItemClickListener(this);


        if (!hasFirstLoad) {
            ProductListTask task = new ProductListTask(this);

            String cid = "2";
            if (categoryId != null) {
                cid = categoryId;
            }
            task.execute(cid, "10");
        }
        return ret;
    }

    @Override
    public void processor(JSONObject result) {
        hasFirstLoad = true;
        if (result != null) {
            try {
                int code = result.getInt("code");
                if (code == 1) {
                    // TODO 正确数据，需要解析
                    JSONObject msg = result.getJSONObject("msg");
                    JSONObject data = msg.getJSONObject("data");
                    Iterator iterator = data.keys();

                    List<Product> productList = new LinkedList<Product>();

                    while (iterator.hasNext()) {
                        String key = (String) iterator.next();
                        JSONObject object = data.getJSONObject(key);
                        Product product = new Product();
                        product.parseJSON(object);
                        productList.add(product);
                    }

                    products.addAll(productList);
                    adapter.notifyDataSetChanged();

                } else {
                    String msg = result.getString("msg");
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int parentId = parent.getId();
        if (parentId == R.id.store_platform) {
            DataStorage dataStorage = DataStorage.getInstance();
            Category category = dataStorage.getCategory("2");

            if (category != null) {
                List<Category> subCategories = category.getSubCategory();
                // 取子分类
                Category cat = subCategories.get(position);
                String catId = cat.getId();

                Intent intent = new Intent(getActivity(), SubCategoryActivity.class);
                intent.putExtra(Constants.INTENT_KEY_CATEGORY_ID, catId);
                startActivity(intent);
            }
        }
    }
}